package com.xkcyy.one.ai.common.tool.factory;

import com.xkcyy.one.ai.common.tool.AbstractAutoDescTool;
import com.xkcyy.one.ai.common.tool.util.JsonSchemaGenerator;
import com.xkcyy.one.ai.llm.model.ToolDefinition;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

/**
 * 工具工厂
 * 用于统一管理工具的创建
 * 
 * @author yuand
 */
@Slf4j
@Component
public class ToolFactory {

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 创建工具实例
     * 
     * @param toolClass 工具类
     * @return 工具实例
     */
    public <T extends AbstractAutoDescTool> T createTool(Class<T> toolClass) {
        try {
            // 生成工具定义
            ToolDefinition definition = JsonSchemaGenerator.generateToolDefinition(toolClass);

            // 创建工具实例
            T tool = toolClass.getDeclaredConstructor(ToolDefinition.class).newInstance(definition);

            // 注入依赖
            applicationContext.getAutowireCapableBeanFactory().autowireBean(tool);

            return tool;
        } catch (Exception e) {
            log.error("Failed to create tool: {}", toolClass.getName(), e);
            throw new RuntimeException("Failed to create tool: " + toolClass.getName(), e);
        }
    }
}